package org.chaos.sekiro.workorder.app.form.internal.dao

import org.chaos.sekiro.common.ktorm.AuditTable
import org.chaos.sekiro.workorder.app.form.internal.dao.Components.bindTo
import org.chaos.sekiro.workorder.app.form.internal.model.Component
import org.chaos.sekiro.workorder.common.enumeration.ComponentType
import org.ktorm.database.Database
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.ktorm.entity.*
import org.ktorm.schema.boolean
import org.ktorm.schema.enum
import org.ktorm.schema.long
import org.ktorm.schema.varchar
import org.springframework.stereotype.Repository
import java.time.LocalDateTime

object Components : AuditTable<Component>("wo_components") {
    val id = long("id").primaryKey().bindTo { it.id }
    val userId = long("user_id").bindTo { it.userId }
    val formId = long("form_id").bindTo { it.formId }
    val parentId = long("parent_id").bindTo { it.parentId }
    val name = varchar("name").bindTo { it.name }
    val type = enum<ComponentType>("type").bindTo { it.type }
    val deleted = boolean("deleted").bindTo { it.deleted }
}

val Database.components get() = this.sequenceOf(Components)

@Repository
class ComponentDao(
    private val database: Database
) {

    fun findByUserIdAndFormIdAndDeleted(userId: Long, formId: Long, deleted: Boolean = false): List<Component> =
        database.components.filter {
            (it.userId eq userId) and
                    (it.formId eq formId) and
                    (it.deleted eq deleted)
        }.toList()

    fun insert(entities: List<Component>) {
        entities.forEach {
            it.createdTime = LocalDateTime.now()
            it.modifiedTime = LocalDateTime.now()
            database.components.add(it)
        }
    }

    fun update(entity: Component) {
        entity.modifiedTime = LocalDateTime.now()
        database.components.update(entity)
    }
}